package com.joker.coupon.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.joker.common.redis.service.RedisService;
import com.joker.common.security.utils.SecurityUtils;
import com.joker.coupon.domain.PmsCoupon;
import com.joker.coupon.domain.PmsOrder;
import com.joker.coupon.domain.PmsUserCoupon;
import com.joker.coupon.mapper.PmsCouponMapper;
import com.joker.coupon.service.PmsCouponService;
import com.joker.system.common.model.LoginUser;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PmsCouponServiceImpl implements PmsCouponService {

    @Autowired
    private PmsCouponMapper pmsCouponMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AlipayConfig alipayConfig;


    /**
     * 首页显示优惠卷
     * @param recommendStatus
     * @return
     */
    @Override
    public List<PmsCoupon> selectHomePageCoupon(Integer recommendStatus) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();

        Date date = new Date();

        List<PmsCoupon> couponList = pmsCouponMapper.selectHomePageCoupon(recommendStatus, userid, date);

        couponListForeach(couponList);

        return couponList;
    }

    /**
     * 领劵
     *
     * @param skuId
     */
    @Transactional
    @Override
    public void receiveCoupon(Long skuId) {

        PmsCoupon pmsCoupon = pmsCouponMapper.selectCouponInfo(skuId);
        Long couponStatus = pmsCoupon.getCouponStatus();
        if (couponStatus == 1){
            throw new RuntimeException("该优惠卷还未开始");
        }

        if (couponStatus == 3){
            throw new RuntimeException("该优惠卷已失效");
        }

        if (couponStatus == 4){
            throw new RuntimeException("该优惠卷已结束");
        }

        Date date = new Date();
        int startDate = date.compareTo(pmsCoupon.getEnableStartTime());
        if (startDate < 0){
            throw new RuntimeException("该优惠卷还未开始");
        }

        int endDate = date.compareTo(pmsCoupon.getEnableEndTime());
        if (endDate > 0){
            throw new RuntimeException("该优惠卷不在领取时间内");
        }

        if (pmsCoupon.getGrantNum() <= 0){
            throw new RuntimeException("该优惠卷已被抢光");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();

        PmsUserCoupon pmsUserCoupon = new PmsUserCoupon();
        pmsUserCoupon.setUserId(userid);
        pmsUserCoupon.setReceiveTime(date);
        pmsUserCoupon.setCouponId(pmsCoupon.getId());
        pmsUserCoupon.setStatus(0L);

        PmsUserCoupon pmsUserCoupon1 = pmsCouponMapper.selectUserCouponInfo(userid, pmsCoupon.getId());
        if (pmsUserCoupon1 != null){
            throw new RuntimeException("您已领取过该优惠卷");
        }

        pmsCouponMapper.receiveCoupon(pmsUserCoupon);

        pmsCouponMapper.updateGrantNum(pmsUserCoupon.getCouponId());

    }

    /**
     * sku详情页显示优惠卷
     * @param skuId
     * @return
     */
    @Override
    public List<PmsCoupon> selectCouponBySkuId(Long skuId) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();

        Date date = new Date();

        List<PmsCoupon> couponList = pmsCouponMapper.selectCouponBySkuId(skuId, userid, date);

        couponListForeach(couponList);

        return couponList;
    }

    /**
     * 购物车页面显示优惠卷
     *
     * @return
     */
    @Override
    public List<PmsCoupon> selectCouponByCart(Long skuId) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();

        Date date = new Date();

        List<PmsCoupon> pmsCoupons = pmsCouponMapper.selectCouponByCart(skuId, userid, date);
        couponListForeach(pmsCoupons);

        if (pmsCoupons.size() > 0){
            for (PmsCoupon pmsCoupon : pmsCoupons) {

                PmsUserCoupon pmsUserCoupon = pmsCouponMapper.selectUserCouponInfo(userid, pmsCoupon.getId());
                if (pmsUserCoupon != null){
                    pmsCoupon.setStatus(pmsUserCoupon.getStatus());
                }
                if (pmsUserCoupon == null){
                    pmsCoupon.setStatus(null);
                }

            }
        }

        return pmsCoupons;

    }

    /**
     * 显示用户已领取优惠卷
     * @param status
     * @return
     */
    @Override
    public List<PmsCoupon> selectUserCoupon(Long status) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();

        List<PmsCoupon> pmsCouponList = pmsCouponMapper.selectUserCoupon(userid, status);
        couponListForeach(pmsCouponList);

        return pmsCouponList;
    }

    /**
     * 下单页面显示用户已领取可使用优惠卷
     * @return
     */
    @Override
    public List<PmsCoupon> selectCouponByOrder() {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();

        List<PmsCoupon> couponList = pmsCouponMapper.selectCouponByOrder(userid);

        couponListForeach(couponList);

        return couponList;
    }

    @Override
    public String generatePay(String totalPrice, Long couponId) throws AlipayApiException {
        PmsOrder pmsOrder = createOrder(couponId);
        // 1. 根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        // 设置商户订单号
        model.setOutTradeNo(RandomUtil.randomNumbers(5));
        // 设置订单总金额
        model.setTotalAmount(totalPrice);
        // 设置订单标题
        model.setSubject("cart_pay");
        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        // 设置PC扫码支付的方式
        model.setQrPayMode("1");
        // 设置商户自定义二维码宽度
        model.setQrcodeWidth(200L);

        // 设置订单包含的商品列表信息
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.MINUTE,30);
        Date time = instance.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置订单绝对超时时间
        model.setTimeExpire(simpleDateFormat.format(time));

        request.setBizModel(model);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if (response.isSuccess()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userid = loginUser.getUserid();

            pmsCouponMapper.updateOrderStatus(pmsOrder.getId(), 1L);
            pmsCouponMapper.updateMyCouponStatus(userid, pmsOrder.getId(), 1L);

            System.out.println("调用成功");
        } else {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userid = loginUser.getUserid();

            pmsCouponMapper.updateOrderStatus(pmsOrder.getId(), 0L);
            pmsCouponMapper.updateMyCouponStatus(userid, pmsOrder.getId(), 1L);

            System.out.println("调用失败");
        }

        return pageRedirectionData;
    }

    @Override
    public PmsCoupon computeDiscountPrice(Long couponId) {

        BigDecimal discountTotalPrice = BigDecimal.valueOf(88888);
        PmsCoupon pmsCoupon = pmsCouponMapper.selectCouponInfo(couponId);

        if (pmsCoupon != null){
            if (pmsCoupon.getCouponType() == 1){
                Long minusPrice = pmsCoupon.getMinusPrice();
                BigDecimal preferentialPrice = discountTotalPrice.subtract(BigDecimal.valueOf(minusPrice));
                pmsCoupon.setDiscountTotalPrice(preferentialPrice);
            }

            if (pmsCoupon.getCouponType() == 2){
                BigDecimal discountNum = BigDecimal.valueOf(pmsCoupon.getDiscountNum() / 100);
                BigDecimal discountPrice = discountTotalPrice.multiply(discountNum);
                pmsCoupon.setDiscountTotalPrice(discountPrice);
            }

            if (pmsCoupon.getCouponType() == 3){

                Integer minimumPrice = pmsCoupon.getMinimumPrice();
                Integer maximumPrice = pmsCoupon.getMaximumPrice();
                int discountPrice = RandomUtils.nextInt(minimumPrice, maximumPrice);
                Long maxDiscountPrice = pmsCoupon.getDiscountPrice();
                //如果优惠券优惠价格大于最大优惠价格，则继续生成优惠券优惠价格，知道小于最大优惠价格
                while (discountPrice > maxDiscountPrice){
                    discountPrice = RandomUtils.nextInt(minimumPrice, maximumPrice);
                    if (discountPrice < maxDiscountPrice){
                        break;
                    }
                }
                BigDecimal randomPrice = discountTotalPrice.subtract(BigDecimal.valueOf(discountPrice));
                pmsCoupon.setDiscountTotalPrice(randomPrice);
            }
        }
        return pmsCoupon;
    }

    public void couponListForeach(List<PmsCoupon> pmsCouponList){
        pmsCouponList.forEach(pmsCoupon -> {
            Long couponType = pmsCoupon.getCouponType();
            if (couponType == 1){
                pmsCoupon.setCouponTypeName("满减券");
                pmsCoupon.setCouponText("￥"+pmsCoupon.getUseThreshold());
                pmsCoupon.setCouponText2("减" + pmsCoupon.getMinusPrice() + "元");
            }
            if (couponType == 2){
                pmsCoupon.setCouponTypeName("折扣券");
                pmsCoupon.setCouponText(pmsCoupon.getDiscountNum() + "折");
                pmsCoupon.setCouponText2("最多优惠"+pmsCoupon.getMaxDiscount()+"元");
            }
            if (couponType == 3){
                pmsCoupon.setCouponTypeName("随机金额劵");
                pmsCoupon.setCouponText("满"+pmsCoupon.getUseThreshold() + "元随机减");
                pmsCoupon.setCouponText2("满"+pmsCoupon.getUseThreshold() + "元随机减");
            }
            Long applyStatus = pmsCoupon.getApplyStatus();
            if (applyStatus == 1){
                pmsCoupon.setApplyStatusName("通用");
            }
            if (applyStatus == 2){
                pmsCoupon.setApplyStatusName("指定商品");
            }
            if (applyStatus == 3){
                pmsCoupon.setApplyStatusName("指定分类");
            }
        });
    }

    /**
     * 生成订单
     */
    public PmsOrder createOrder(Long couponId) {

        PmsOrder pmsOrder = new PmsOrder();
        PmsCoupon pmsCoupon = computeDiscountPrice(couponId);
        if (couponId != null){

            BigDecimal discountTotalPrice = pmsCoupon.getDiscountTotalPrice();

            pmsOrder.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
            pmsOrder.setUserId(SecurityUtils.getLoginUser().getUserid());
            pmsOrder.setTotalPrice(discountTotalPrice);

            pmsCouponMapper.generateOrder(pmsOrder);
        }

        if (couponId == null){

            BigDecimal discountTotalPrice = BigDecimal.valueOf(88888);

            pmsOrder.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
            pmsOrder.setUserId(SecurityUtils.getLoginUser().getUserid());
            pmsOrder.setTotalPrice(discountTotalPrice);

            pmsCouponMapper.generateOrder(pmsOrder);
        }
        return pmsOrder;
    }

}
